﻿using Microsoft.AspNetCore.SignalR;
using System.Text.RegularExpressions;

namespace SignalRWebAPI.Hubs
{
    public class ChatHub : Hub
    {
        /// <summary>
        /// 给所有人发消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task SendMsg(long userId, string msg)
        {
            string sendMsg = $"用户名{Context.ConnectionId}：{msg}";

            //服务端推送给 除自已以外 的所有客户端
            //await Clients.Others.SendAsync("ReceiveMsg", sendMsg);

            //服务端推送给所有客户端
            await Clients.All.SendAsync("ReceiveMsg", sendMsg);

        }
        /// <summary>
        /// 给指定人员发消息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public async Task SendMessageToUser(string userId, string message)
        {
            // 确保用户ID是有效的
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("Invalid user ID", nameof(userId));
            } 
            await Clients.Client(userId).SendAsync("ReceiveToUserMsg", message);
        }

        //客户端成功连接时，会触发此方法
        public override Task OnConnectedAsync()
        {
            var cid = Context.ConnectionId;

            //根据id获取指定客户端
            var client = Clients.Client(cid); 
            return Task.CompletedTask;
        }

        //客户端断开连接时，会触发此方法
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            return Task.CompletedTask;
        }


        /// <summary>
        /// 给群内成员发消息
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="message"></param>
        /// <returns></returns>

        public async Task SendGroupMsg(string groupName, string message)
        {
            await Clients.Group(groupName).SendAsync("SendGroup", $"群内成员：{message}");
        }


        /// <summary>
        /// 创建群
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public async Task AddToGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).SendAsync("SendGroup", $"{Context.ConnectionId} 加入 {groupName}.");
        }
        /// <summary>
        /// 退群
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public async Task RemoveFromGroup(string groupName)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).SendAsync("SendGroup", $"{Context.ConnectionId} 退出 {groupName}.");
        }
    }
}
